package cn.agiledata.bank.transaction.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cfca.sm2rsa.common.PKIException;
import cfca.util.cipher.lib.JCrypto;
import cfca.util.cipher.lib.Session;
import cn.agiledata.bank.account.service.IAccountService;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.ActionTypeTemplate;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.ConvertUtil;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.SignUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.facade.ServiceFacade;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.ActionType;
import cn.agiledata.bank.hibernateBean.MoneyRole;
import cn.agiledata.bank.hibernateBean.QdTransDetail;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.login.form.MobileLoginForm;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.transaction.bean.CapitalDetailBean;
import cn.agiledata.bank.transaction.bean.JsonRequestBean;
import cn.agiledata.bank.transaction.dao.ActionTypeDao;
import cn.agiledata.bank.transaction.exception.TransactionException;
import cn.agiledata.bank.transaction.service.GetTransactionImpl;
import cn.agiledata.bank.transaction.service.TransactionFactory;

import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class MobileTransAction extends DispatchAction implements
		java.io.Serializable, Constant {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5600844598664739967L;
	// private static final String url = "http://59.175.217.22:8081/puc/user";
	public static final String SESS_VERICODE = "sys_sess_vericode";

	public static final String SESS_SMS_VERICODE = "sys_sess_sms_vericode";

	public static final String SESS_SMS_MOBILE = "sys_sess_sms_mobile";
	public static final long TIME_OUT_SESSION=600000;
	 public static  byte[] signInfo=null;
	 private TransactionTemplate transactionTemplate;
	protected IMySpaceService getMySpaceService() throws IPBException {
		return (IMySpaceService) IPBAppFactory.getObj("mySpaceService");
	}
	protected TransactionTemplate getTransactionTemplate() throws IPBException {
		return (TransactionTemplate) IPBAppFactory.getObj("transactionTemplate");
	}
	protected ActionTypeDao getActionTypeDao() throws IPBException {
		return (ActionTypeDao) IPBAppFactory.getObj("actionTypeDao");
	}
	protected AccountTemplateInter getAccountTemplate() throws IPBException {
		return (AccountTemplateInter) IPBAppFactory.getObj("accountTemplate");
	}
	protected ServiceFacade sf = (ServiceFacade) IPBAppFactory
			.getObj("serviceFacade");

	protected IAccountService getAccountService() throws IPBException {
		return (IAccountService) IPBAppFactory.getObj("accountService");
	}

	public int hasAccessPermission(int accessLevel, HttpServletRequest request)
			throws IPBException {
		int result = 1;
		return result;
	}
    public static Session session = null;
    //软库初始化
    static {
        try {
			JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, null);
			session = JCrypto.getInstance().openSession(JCrypto.JSOFT_LIB);
		} catch (PKIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
    }
	/**
	 * 手机登录
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward mobileLogon(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map map = (Map) this.servlet.getServletContext().getAttribute(
				Constant.MOBILE_SESSION_SIGN);
		Date date=new Date();
		if (map == null) {
			map = new HashMap();
		}
		// 登录渠道 mobile-手机
		MobileLoginForm theForm = (MobileLoginForm) form;
		JSONObject jsonObj = new JSONObject();
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account == null) {
			jsonObj.put("retCode", "999999");
			jsonObj.put("errmsg", "手机号码不存在！");
		} else if (account.getStatus().equals("3")) {
			jsonObj.put("retCode", "999997");
			jsonObj.put("errmsg", "账户已经冻结！");
		} else if (this.getAccountService().checkBlackList(account.getEmail())) {
			jsonObj.put("retCode", "999987");
			jsonObj.put("errmsg", "用户已被加入黑名单，禁止登录！");
		} else {
			 if (map.containsKey(theForm.getPhoneNo())) {
		    	   Date date1 = (Date) map.get(theForm.getPhoneNo());
				   long x = date.getTime() - date1.getTime();
				   if (x>TIME_OUT_SESSION){
					account.setLoginStatus(0);
					this.getAccountService().update(account);
				      }
				}
				Date overDate = DateUtil.addDate(account.getUpdateTime(), 0, 0,
						Constant.PASSWORD_OVERDATE_DAY);
				if (new Date().after(overDate)) {
					jsonObj.put("retCode", "888882");
					jsonObj.put("errmsg", "密码已过期");
					response.setHeader("Content-type", "textml;charset=UTF-8");
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write(jsonObj.toString());
					response.getWriter().flush();
					response.getWriter().close();
					return null;
				}
			if (account.getLoginStatus() == 1) {
				jsonObj.put("retCode", "888887");
				jsonObj.put("errmsg", "账户已登录!");
				response.setHeader("Content-type", "textml;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				response.getWriter().write(jsonObj.toString());
				response.getWriter().flush();
				response.getWriter().close();
				return null;
			}
			if ((theForm.getLoginPwd() != null)
					&& (!account.getLoginPassword().equals(
							theForm.getLoginPwd().trim()))) {
				jsonObj.put("retCode", "999991");
				jsonObj.put("errmsg", "用户名、登录密码不相符。");
			} else {

				jsonObj.put("retCode", "000000");
				jsonObj.put("userName", account.getName());
				jsonObj.put("accountId", account.getId().toString());
				jsonObj.put("acctId", account.getAccountId());
				jsonObj.put("balance", account.getDefaultSubAccount()
						.getAccountBalance().getBalance());
				String strKey = account.getKey();
				// FIXME 临时处理，需要修改
				if(StringUtils.isBlank(strKey)) {
					strKey = "1123456";
				}
				jsonObj.put("signMsg", SignUtil.sign(strKey));
			}
		}
		map.put(theForm.getPhoneNo(), date);
		this.servlet.getServletContext().setAttribute(
				Constant.MOBILE_SESSION_SIGN, map);
		account.setLoginStatus(1);
		this.getAccountService().update(account);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 手机查询余额
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getBalanceFromMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getPhoneNo());
		System.out.println(theForm.getPayPwd());
		JSONObject jsonObj = new JSONObject();
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account == null) {
			jsonObj.put("retCode", "999999");
			jsonObj.put("errmsg", "手机号码不存在！");
		} else {
			if ((theForm.getPayPwd() != null)
					&& (!account.getPayPassword().equals(
							theForm.getPayPwd().trim()))) {
				jsonObj.put("retCode", "999992");
				jsonObj.put("errmsg", "用户名、支付密码不相符。");
			} else {
				jsonObj.put("retCode", "000000");
				jsonObj.put("balance", account.getDefaultSubAccount()
						.getAccountBalance().getBalance());
			}
		}
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;

	}

	/**
	 * 获取交易记录
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getTransHisFromMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getPhoneNo());
		System.out.println(theForm.getLoginPwd());
		System.out.println(theForm.getStartTime());
		System.out.println(theForm.getEndTime());
		JSONObject jsonObj = new JSONObject();
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account == null) {
			jsonObj.put("retCode", "999999");
			jsonObj.put("errmsg", "手机号码不存在！");
		} else {
			if ((theForm.getLoginPwd() != null)
					&& (!account.getLoginPassword().equals(
							theForm.getLoginPwd().trim()))) {
				jsonObj.put("retCode", "999992");
				jsonObj.put("errmsg", "用户名、支付密码不相符。");
			} else {
				List result = this.getAccountService().findTransHisByPara(
						account.getDefaultSubAccount().getId(), theForm.getStartTime(),
						theForm.getEndTime());
				if (result != null) {
					List resultList = new ArrayList();
					for (int i = 0; i < result.size(); i++) {
						CapitalDetailBean bean = (CapitalDetailBean) result
								.get(i);
						resultList.add(bean);
					}

					JSONArray ja = JSONArray.fromObject(resultList);
					jsonObj.put("retCode", "000000");
					jsonObj.put("resultList", ja);
				} else {
					jsonObj.put("retCode", "999995");
					jsonObj.put("description", "没有交易记录！");
				}
			}
		}
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 发送手机激活码
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward activeFromMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		JSONObject jsonObj = new JSONObject();
		System.out.println(theForm.getPhoneNo());

		Map map = new HashMap();
		String retCode = "000000";
		String errmsg = "";
		map.put("register_mobile", theForm.getPhoneNo());
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account != null) {
			retCode = "999996";
			errmsg = "手机号已被使用！";
		} else {

			String code = this.sf.smsVerify2(map);
			setSessionAttribute(SESS_SMS_VERICODE, code + "#"
					+ theForm.getPhoneNo().trim(), request);
			setSessionAttribute(SESS_SMS_MOBILE, theForm.getPhoneNo().trim(),
					request);
			jsonObj.put("actUuid", code + "#" + theForm.getPhoneNo().trim());
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 用户注册
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward registerFromMobile(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		String retCode = "000000";
		String errmsg = "";
		String result = this.mobileConfirm(request, theForm);
		if (result.equals("1")) {
			retCode = "999997";
			errmsg = "未申请激活码！";
		} else if (result.equals("2")) {
			retCode = "999998";
			errmsg = "激活码无效！";
		} else if(theForm.getPayPwd().equals(theForm.getLoginPwd())) {
			retCode = "999994";
			errmsg = "登录密码不能与支付密码相同！";
		} else {
			System.out.println(theForm.getPhoneNo());
			System.out.println(theForm.getLoginPwd());
			System.out.println(theForm.getIdCardNo());
			System.out.println(theForm.getUserName());
			System.out.println(theForm.getPayPwd());
			Map map = new HashMap();
			map.put("email", null);
			map.put("mobile", theForm.getPhoneNo());
			map.put("type", "A");
			map.put("corpName", null);
			map.put("corpTel", null);
			map.put("corpLicenceNo", null);
			map.put("corpZip", null);
			map.put("corpAddr", null);
			map.put("corpFinanceName", null);
			map.put("corpBossId", null);
			map.put("capitalAmount", null);
			map.put("prinName", null);
			map.put("corpAccountLicenceNo", null);
			map.put("corpOrganizeNo", null);
			map.put("corpTaxId", null);
			map.put("loginPassword", theForm.getLoginPwd());
			map.put("payPassword", theForm.getPayPwd());
			map.put("personName", theForm.getUserName());
			map.put("idCardNo", theForm.getIdCardNo());
			map.put("gender", theForm.getSex());
			map.put("adminId", null);
			map.put("url", ConvertUtil.getRequestURL(request));
			WebUtil.removeSessionAttribute(request, SESS_SMS_MOBILE);
			WebUtil.removeSessionAttribute(request, SESS_SMS_VERICODE);
			try {
				this.getAccountService().userRegister("1", "webpay", map);
			} catch (Exception ex) {
				retCode = "999999";
				ex.printStackTrace();
			}
		}
		JSONObject jsonObj = new JSONObject();
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}


	/**
	 * 修改用户信息
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward updateAccountInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getPhoneNo());
		System.out.println(theForm.getAddr());
		System.out.println(theForm.getLoginPwd());
		System.out.println(theForm.getSex());
		System.out.println(theForm.getTel());
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account == null) {
			retCode = "999999";
			errmsg = "手机号码不存在！";
		} else {
			if ((theForm.getLoginPwd() != null)
					&& (!account.getLoginPassword().equals(
							theForm.getLoginPwd().trim()))) {
				retCode = "999991";
				errmsg = "用户名、登录密码不相符。";
			} else {
				account.setAddr(theForm.getAddr());
				if (!theForm.getBirthday().equals("")) {
					DateFormat format = new SimpleDateFormat("yyyyMMdd");
					account.setBirthday(format.parse(theForm.getBirthday()));
				}
				account.setGender(theForm.getSex());
				account.setTel(theForm.getTel());
				try {
					this.getMySpaceService().saveOrUpdateAccount(account, null,
							null);
				} catch (Exception ex) {
					retCode = "999994";
					errmsg = "修改失败！";
					ex.printStackTrace();
				}
				retCode = "000000";
			}
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public ActionForward updateLoginPwd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getPhoneNo());
		System.out.println(theForm.getLoginPwd());
		System.out.println(theForm.getNewLgPwd());
		JSONObject jsonObj = new JSONObject();
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		String retCode = "000000";
		String errmsg = "";
		if (account == null) {
			retCode = "999999";
			errmsg = "手机号码不存在！";
		} else {
			if ((theForm.getLoginPwd() != null)
					&& (!account.getLoginPassword().equals(
							theForm.getLoginPwd().trim()))) {
				retCode = "999991";
				errmsg = "用户名、原登录密码不相符！";
			} else if (account.getPayPassword().equals(
					theForm.getNewLgPwd().trim())) {
				retCode="999994";
				errmsg = "登录密码不能与支付密码相同！";
			} else {
				account.setLoginPassword(theForm.getNewLgPwd());
			}

		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public ActionForward updatePayPwd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getPhoneNo());
		System.out.println(theForm.getPayPwd());
		System.out.println(theForm.getNewPayPwd());
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		if (account == null) {
			retCode = "999999";
			errmsg = "手机号码不存在！";
		} else {
			if ((theForm.getPayPwd() != null)
					&& (!account.getPayPassword().equals(
							theForm.getPayPwd().trim()))) {
				retCode = "999991";
				errmsg = "用户名、原支付密码不相符。";
			} else if (account.getLoginPassword().equals(
					theForm.getNewPayPwd().trim())) {
				retCode="999994";
				errmsg = "登录密码不能与支付密码相同！";
			} else {
				try {
					account.setPayPassword(theForm.getNewPayPwd());
				} catch (Exception ex) {
					retCode = "999994";
					errmsg = "修改失败！";
					ex.printStackTrace();
				}

			}
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	private String getActionInfo(JsonRequestBean requestBean) {
		String retStr = "{";
		retStr += "\"IS_DEFAULT\":" + requestBean.getIS_DEFAULT() + ",";
		retStr += "\"PHONE\":" + "\"" + requestBean.getPHONE() + "\"";
		retStr += "}";
		System.out.println(retStr + "*****************");
		return retStr;
	}

	/**
	 * 新的手机验证
	 * 
	 * @param form
	 * @return
	 * @throws BusinessException
	 */
	public String mobileConfirm(HttpServletRequest request, MobileLoginForm form)
			throws BusinessException {
		String vericode = form.getActiveCode();

		// String snap = (String) WebUtil.getSessionString(request,
		// SESS_SMS_VERICODE);
		String snap = form.getActUuid();
		if (snap == null) {
			return "1";
		}
		String[] tuple = snap.split("#");

		if (!vericode.equals(tuple[0])) {
			return "2";
		}

		String mobile = tuple[1];
		WebUtil.setSessionString(request, SESS_SMS_MOBILE, mobile);
		return mobile;
	}
	public ActionForward signInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		JSONObject jsonObj=new JSONObject();
		String retCode="000000";
		String errmsg="";
		MobileLoginForm theForm = (MobileLoginForm) form;
		try {
			UUID uuid = UUID.randomUUID();
			System.out.println(uuid.toString());
			System.out.println(SignUtil.sign(uuid.toString()));
        } catch (Exception e) {
			e.printStackTrace();
		}
    	jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 创建或者修改订单信息
	 * 
	 * @param request
	 * @param form
	 * @return
	 */
	public ActionForward createOrUpdateQdTrans(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String retCode = "000000";
		String errmsg = "";
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println("createOrUpdateQdTrans step1");
		JSONObject jsonObj = new JSONObject();
		QdTransDetail detail;
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getAccountId());
		Account acctMer = getAccountTemplate().getAccountByAccountId("11");
		
		String accountId = request.getParameter("accountId");
		String payAmount = request.getParameter("payAmount");
		String orderId = request.getParameter("orderId");
		String phoneNo = request.getParameter("phoneNo");
		String changeAmount = request.getParameter("changeAmount");

		StringBuffer plain = new StringBuffer();
		plain.append("accountId=").append(accountId);
		plain.append("&payAmount=").append(payAmount);
		plain.append("&orderId=").append(orderId);
		plain.append("&phoneNo=").append(phoneNo);
		plain.append("&changeAmount=").append(changeAmount);
		
		if (account == null) {
			retCode = "999995";
			errmsg = "账户不存在";
		} else if(!SignUtil.validateSign(plain.toString(), theForm.getSignMsg(),acctMer.getAccountId())) {
			// 验签
			retCode = "999984";
			errmsg = "验签失败";
		} else if(!acctMer.getStatus().equals(Constant.ACCOUNT_STATE_NORMAL)) {
			// 商户状态异常
			retCode = "999986";
			errmsg = "商户状态异常，不允许交易";
		} else if(this.getAccountService().checkBlackList(acctMer.getEmail())) {
			// 商户状态异常
			retCode = "999987";
			errmsg = "此商户为黑名单商户，不允许交易";
			MoneyRole mr = new MoneyRole();
			mr.setCodename("黑名单商户交易");
			getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
		} else if(account.getDefaultSubAccount().getAccountBalance().getBalance().compareTo(new Double(payAmount)) < 0) {
			// 账户余额不足
			retCode = "999988";
			errmsg = "账户余额不足";
		}else {
			try {
				
				detail = this.getAccountService().findDetailByOrderId(
						theForm.getOrderId());
				if (detail == null) {
					detail = new QdTransDetail();
				}
				detail.setCreditSeq(account.getDefaultSubAccount().getId());
				if (!(theForm.getPayAmount().equals(""))) {
					detail.setAmount(Double.valueOf(theForm.getPayAmount()));
				}
				if (!(theForm.getChangeAmount().equals(""))) {
					detail.setReturnAmount(Double.valueOf(theForm
							.getChangeAmount()));
				}
				if (!theForm.getBanNo().equals("")) {
					detail.setOrderId(theForm.getBanNo());
				}
				detail.setTransId(theForm.getOrderId());
				detail.setActionSeq(Long.valueOf("99"));
				if (!theForm.getPhoneNo().equals("")) {
					detail.setRemark(theForm.getPhoneNo());
				}
				if (!theForm.getPayDate().equals("")) {
					DateFormat format = new SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");
					try {
						Date date = format.parse(theForm.getPayDate());
						detail.setCreateTime(date);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				if (!theForm.getBanNo().equals("")) {
					detail.setBankSeq(Long.valueOf(theForm.getBanNo()));
				}
				detail.setTransStatus(theForm.getStatus());
				this.getAccountService().saveOrUpdateTransDetail(detail);

				//
				Transaction trans = null;
				String transId = theForm.getOrderId();
				transId = DateUtil.date2String(new Date(),"yyyyMMddHHmmss");
				if (transId != null) {
					trans = getTransactionTemplate()
							.getTransactionByTranId(transId);
				} else {
					transId = UniqueIdentityUtil.getTransactionSequence();
				}
				if (trans == null) {
					trans = new Transaction();
					trans.setTransId(transId);
				}
				if (trans.getId() == null) {// 若为新建交易
					trans.setDebit(account.getDefaultSubAccount());
					
					// FIXME  增加商户黑名单控制
					
					trans.setCredit(getAccountTemplate()
							.getSubAccountByAccountId("11"));
					trans.setUpdateTime(new Date());
					trans.setCreateTime(new Date());
					trans.setActionType(getActionTypeDao()
							.getActionType(6L));
					// 需要确认的交易，内部状态设为'N'，交易状态为"待银行反馈"
					trans.setInsideStatus(Constant.INSIDE_STATUS_NO);
					if("88".equals(theForm.getStatus())) {
						trans.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
					}
					else {
						trans.setTransStatus(Constant.TRANS_STATUS_WAITEBANKFEEDBACK);
					}
					trans.setBeginDate(new Date());
					trans.setAmount(Double.valueOf(theForm
							.getChangeAmount()));
					trans.setCreateUser(theForm.getAccountId());
					saveTransaction(trans);
				} else {
					trans.setUpdateTime(new Date());
					trans.setUpdateUser(trans.getCredit().getAccount()
							.getAccountId());
				}

			} catch (NumberFormatException e) {
				retCode = "999994";
				errmsg = "创建或者更新失败订单失败！";
				e.printStackTrace();
			} catch (BusinessException e) {
				retCode = "999994";
				errmsg = "创建或者更新失败订单失败！";
				e.printStackTrace();
			} catch (IPBException e) {
				retCode = "999994";
				errmsg = "创建或者更新失败订单失败！";
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}
		// } else {
		// retCode = "999990";
		// errmsg = "校验mac错！";
		// }
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 查询订单信息
	 * 
	 * @param request
	 * @param form
	 * @return
	 */
	public ActionForward searchTransDetail(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getOrderId());
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		QdTransDetail detail = null;
		try {
			detail = this.getAccountService().findDetailByOrderId(
					theForm.getOrderId());
			if (detail == null) {
				retCode = "999990";
				errmsg = "订单信息不存在";
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IPBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		CapitalDetailBean bean = new CapitalDetailBean();
		BeanUtils.copyProperties(bean, detail);
		jsonObj.put("retCode", retCode);
		jsonObj.put("detail", bean);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 撤销订单信息
	 * 
	 * @param request
	 * @param form
	 * @return
	 */
	public ActionForward cancelOrder(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		System.out.println(theForm.getOrderId());
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		QdTransDetail detail = null;
		try {
			detail = this.getAccountService().findDetailByOrderId(
					theForm.getOrderId());
			if (detail == null) {
				retCode = "999990";
				errmsg = "订单信息不存在";
			} else {
				detail.setCreditSeq(detail.getCreditSeq());
				detail.setTransStatus("91");
				this.getAccountService().saveOrUpdateTransDetail(detail);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IPBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public void setSessionAttribute(String key, Object value,
			HttpServletRequest request) {
		getSession(request).setAttribute(key, value);
	}

	public void removeSessionAttribute(String key, HttpServletRequest request) {
		getSession(request).removeAttribute(key);
	}

	public HttpSession getSession(HttpServletRequest request) {
		HttpSession sess = null;

		try {
			sess = request.getSession();
		} catch (RuntimeException e) {
			e.printStackTrace();
		}

		return sess;

	}

	/***************************************************************************
	 * 企业账户状态查询
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward getAccountStatus(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		System.out.println(theForm.getAccountId());
		try {
			Account account = this.getAccountService().findAccountByEmail(
					theForm.getAccountId());
			if (account == null) {
				retCode = "999995";
				errmsg = "商户不存在";
			} else {
				jsonObj.put("status", account.getStatus());
			}
		} catch (BusinessException e) {
			errmsg = "系统错，查询失败";
			e.printStackTrace();
		} catch (IPBException e) {
			errmsg = "系统错，查询失败";
			e.printStackTrace();
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/***************************************************************************
	 * 检查交易是否符合交易规则
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward checkRule(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		// theForm.setPhoneNo("18062511980");
		// theForm.setPayAmount("60");
		System.out.println("#########################:" + getAccountTemplate().getAccountByAccountId("11").getEmail());
		JSONObject jsonObj = new JSONObject();
		String retCode = "000000";
		String errmsg = "";
		System.out.println(theForm.getAccountId());
		try {
			Account account = this.getAccountService().findAccountByEmail(
					theForm.getPhoneNo());
			if (account == null) {
				retCode = "999995";
				errmsg = "商户不存在";
			}
			List listRule = this.getAccountService().getRule();
			for (Object object : listRule) {
				MoneyRole mr = (MoneyRole) object;
				System.out.println("-------------" + mr.getCode());
				if (mr.getCode().equals(Constant.CODE_12)) {
					if (Double.valueOf(theForm.getPayAmount()) > mr
							.getCodevalue()) {
						retCode = "888885";
						errmsg = "该订单金额超过单笔金额限制";
						getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
						break;
					}
					continue;
				}
				Object sign = this.getAccountService().statQdTransDetail(
						account.getId(), mr.getCode());
				List listCode = new ArrayList();
				listCode.add(Constant.CODE_16);
				listCode.add(Constant.CODE_13);
				if (listCode.contains(mr.getCode())) {
					Double money = Double.valueOf(sign.toString());
					money += Double.valueOf(theForm.getPayAmount().toString());
					if (money > mr.getCodevalue()) {
						if (mr.getCode().equals(Constant.CODE_16)) {
							retCode = "888881";
							errmsg = "本月累计充值金额达到上限";
							getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
							break;
						}
						if (mr.getCode().equals(Constant.CODE_13)) {
							retCode = "888882";
							errmsg = "今日累计充值金额达到上限";
							getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
							break;
						}
					}
				}
				listCode = new ArrayList();
				listCode.add(Constant.CODE_14);
				listCode.add(Constant.CODE_15);
				if (listCode.contains(mr.getCode())) {
					int count = Integer.valueOf(sign.toString());
					count += 1;
					if (count > mr.getCodevalue()) {
						if (mr.getCode().equals(Constant.CODE_15)) {
							retCode = "888883";
							errmsg = "本月累计充值次数达到上限";
							getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
							break;
						}
						if (mr.getCode().equals(Constant.CODE_14)) {
							retCode = "888884";
							errmsg = "今日累计充值次数达到上限";
							getAccountTemplate().noticeMoenyRole(mr, theForm.getPayAmount(), account);
							break;
						}
					}
				}
			}
		} catch (BusinessException e) {
			errmsg = "系统错，查询失败";
			e.printStackTrace();
		} catch (IPBException e) {
			errmsg = "系统错，查询失败";
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public ActionForward checkSession(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		Map map = (Map) this.servlet.getServletContext().getAttribute(
				Constant.MOBILE_SESSION_SIGN);
		JSONObject jsonObj = new JSONObject();
		if (map == null) {
			map = new HashMap();
		}
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		String retCode = "000000";
		String errmsg = "";
		if (account == null) {
			retCode = "999995";
			errmsg = "商户不存在";
		}
		Date date = new Date();
		if (!map.containsKey(theForm.getPhoneNo())) {
			retCode = "888889";
			errmsg = "session违法";
		} else {
			Date date1 = (Date) map.get(theForm.getPhoneNo());
			long x = date.getTime() - date1.getTime();
			if (x > TIME_OUT_SESSION) {
				retCode = "888886";
				errmsg = "session超时";
				account.setLoginStatus(0);
				this.getAccountService().update(account);
			} else {
				map.put(theForm.getPhoneNo(), date);
			}
		}

		this.servlet.getServletContext().setAttribute(
				Constant.MOBILE_SESSION_SIGN, map);
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public ActionForward shutdown(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		MobileLoginForm theForm = (MobileLoginForm) form;
		Map map = (Map) this.servlet.getServletContext().getAttribute(
				Constant.MOBILE_SESSION_SIGN);
		JSONObject jsonObj = new JSONObject();
		if (map == null) {
			map = new HashMap();
		}
		Account account = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
		String retCode = "000000";
		String errmsg = "";
		if (account == null) {
			retCode = "999995";
			errmsg = "商户不存在";
		}
		if (map.containsKey(theForm.getPhoneNo())) {
			map.remove(theForm.getPhoneNo());
		}
		this.servlet.getServletContext().setAttribute(
				Constant.MOBILE_SESSION_SIGN, map);
		account.setLoginStatus(0);
		this.getAccountService().update(account);
		jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println("*************************************");
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	public static void main(String[] args) {
		Double xDouble = new Double(2d);
		int i = 1;
		System.out.println(xDouble > i);
	}
    private void saveTransaction(Transaction tran) {
        ActionType actionType = tran.getActionType();
        TransactionFactory tranFactory = new GetTransactionImpl()
                .getTransaction(actionType.getId().toString());
        tranFactory.saveTransaction(tran);
    }
    
    /**
     * 账户间转账
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward transfer(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	System.out.println("transfer invoke.....................");
    	String retCode = "000000";
		String errmsg = "";
        MobileLoginForm theForm = (MobileLoginForm) actionForm;
        Account acctDebit = this.getAccountService().findAccountByEmail(
				theForm.getPhoneNo());
        SubAccount debitSubAccount = acctDebit.getDefaultSubAccount();
        
        // 校验付款方支付密码
        if(StringUtils.isBlank(theForm.getPayPwd()) 
        		||  !acctDebit.getPayPassword().equals(theForm.getPayPwd())) {
        	// 支付密码为空或不正确，返回错误
        	retCode="999992";
        	errmsg="用户名、支付密码不相符。";
        }
        else {
	        // 加载并校验收款方账户信息
	        Account acctCredit =  this.getAccountService().findAccountByEmail(
					theForm.getReceivePhone());
	        String accountType = acctDebit.getAccountType();
	        if (acctCredit.getAccountId().equals("11") && accountType.equals(Constant.ACCOUNT_TYPE_CORPORATION)) {
	        	return null;
	        }
	
	        try {
	
	            Double amount = new Double(theForm.getPayAmount());
	
	            Transaction trans = new Transaction();
	            // 新建交易生成交易编号
	            trans.setTransId(UniqueIdentityUtil.getTransactionSequence());
	            trans.setCreateTime(new Date());
	            String createUser = debitSubAccount.getAccount().getId().toString();
	            trans.setCreateUser(createUser);
	            // 付款方
	            trans.setDebit(debitSubAccount);
	            // 收款方
	            trans.setCredit(acctCredit.getDefaultSubAccount());
	            // 设置交易状态
	            // 非担保交易
	            trans.setTradeType(Constant.TRADE_TYPE_NOASSURE);
	            // 非担保交易的交易状态：交易成功
	            trans.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
	            // 非担保交易的内部状态：进行实际转账操作
	            trans.setInsideStatus(Constant.INSIDE_STATUS_YES);
	            trans.setEndDate(new Date());//设置截止日期
		        // 设置记账模型
		        trans.setOperate(Constant.MODEL_TYPE_PAYMONEY);
	            // 交易类型
	            trans.setActionType(getActionTypeTemplate().getActionTypeById(new Long(Constant.ACTION_TYPE_C)));
	            // 交易金额
	            trans.setAmount(amount);
	            // 付款方费率
	            /*double debitFee = getFeeRatioService().getDebitFee(trans);
	            trans.setDebitFee(new Double(debitFee));*/
	            // 收款方费率
	            /*double creditFee = getFeeRatioService().getCreditFee(trans);
	            trans.setCreditFee(new Double(creditFee));*/
	            // 更新时间和用户
	            trans.setUpdateTime(new Date());
	            trans.setUpdateUser(debitSubAccount.getAccount().getId().toString());
	            // 交易开始时间
	            trans.setBeginDate(new Date());
	            // 商品信息
	//            trans.setCommodityInfo(innerTransactForm.getCommodity());
	            // 用途
	//            trans.setPurpose(innerTransactForm.getPurpose());
	            // 备注
	            trans.setRemark(theForm.getRemark());
	            
	            try {
	                // 保存交易对方记录
	                Account account = trans.getDebit().getAccount(); // 交易本方为付款方
	                Account peerAccount = trans.getCredit().getAccount(); // 交易对方为收款方
	
	                // 保存交易，并更新账户金额限制信息
	                getTransactionTemplate().saveTransactionWithAccountLimit(
	                        trans, acctDebit);
	            } catch (RuntimeException e) {
	            	retCode="9999";
	            	errmsg="交易失败";
	            }
	        } catch (TransactionException e) {
	        	retCode="9999";
	        	errmsg="交易失败";
	        }
        }
        
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("retCode", retCode);
		jsonObj.put("errmsg", errmsg);
		response.setHeader("Content-type", "textml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(jsonObj.toString());
		System.out.println(jsonObj.toString());
		response.getWriter().flush();
		response.getWriter().close();
		return null;
    }
    
    protected final ActionTypeTemplate getActionTypeTemplate() {
        return (ActionTypeTemplate) IPBAppFactory
                .getObj(ForeDict.ACTION_TYPE_TEMPLATE);
    }
    
}
